package com.bsoft.controller;

import com.bsoft.Producer.Demo01Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CountDownLatch;

@Slf4j
@RestController
public class ProducterController {
    @Autowired
    private Demo01Product demo01Product;

    @GetMapping("/testSynSend")
    public void testSynSend() throws InterruptedException {
        int id = (int) (System.currentTimeMillis() / 1000);
        demo01Product.syncSend(id);
        log.info("[testSyncSend][发送编号：[{}] 发送成功]", id);
        //阻塞等待 保证消费
        new CountDownLatch(1).await();

    }

    @GetMapping("/testSendDefault")
    public void testSendDefault() {
        int id = (int) (System.currentTimeMillis() / 1000);
        demo01Product.synSendDefault(id);
        log.info("[tesSyncSendDefault][发送编号：[{}] 发送成功]", id);
    }

    //异步发送消息
    @GetMapping("/testAsynSend")
    public void testAsynSend() throws InterruptedException {
        int id = (int) (System.currentTimeMillis() / 1000);
        demo01Product.asynSend(id).addCallback(new ListenableFutureCallback<Void>() {
            @Override
            public void onFailure(Throwable throwable) {
                log.info("[testASyncSend][发送编号：[{}] 发送异常]]", id, throwable);
            }

            @Override
            public void onSuccess(Void unused) {
                log.info("[testASyncSend][发送编号：[{}] 发送成功，发送成功]", id);
            }
        });
        log.info("[testASyncSend][发送编号：[{}] 调用完成]", id);
        //阻塞 保证成功被消费
        new CountDownLatch(1).await();
    }
}
